/*
 * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.i360day.invoker;

import com.i360day.invoker.codes.encoder.Encoder;
import com.i360day.invoker.properties.HttpInvokerProperties;
import com.i360day.invoker.support.RemoteInvocation;
import com.i360day.invoker.support.RemoteInvocationFactory;
import com.i360day.invoker.support.RemoteInvocationResult;
import com.i360day.invoker.support.RemoteInvocationSerializingExporter;
import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author: liju.z
 * @date: 2024/3/20 11:08
 */
public class AmqpInvokerServiceExporter extends RemoteInvocationSerializingExporter implements InitializingBean, SmartInitializingSingleton {
    private final RemoteInvocationFactory remoteInvocationFactory;
    private final Encoder encoder;
    private final SimpleRabbitmqTemplate simpleRabbitmqTemplate;
    private final HttpInvokerProperties httpInvokerProperties;
    private String exchangeKey;
    private String routingKey;
    private String queueKey;
    private int listenerCount = 1;

    public AmqpInvokerServiceExporter(HttpInvokerProperties httpInvokerProperties, Encoder encoder, RemoteInvocationFactory remoteInvocationFactory, ConnectionFactory connectionFactory) {
        this.httpInvokerProperties = httpInvokerProperties;
        this.encoder = encoder;
        this.remoteInvocationFactory = remoteInvocationFactory;
        this.simpleRabbitmqTemplate = new SimpleRabbitmqTemplate(connectionFactory);
    }

    public void setExchangeKey(String exchangeKey) {
        this.exchangeKey = exchangeKey;
    }

    public void setRoutingKey(String routingKey) {
        this.routingKey = routingKey;
    }

    public void setQueueKey(String queueKey) {
        this.queueKey = queueKey;
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        //声明交换机
        Exchange exchange = new TopicExchange(exchangeKey, true, false, new HashMap<>());
        //声明队列
        Queue queue = new Queue(queueKey, true, false, false, new HashMap<>());
        //绑定
        Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey).and(new HashMap<>() {
            {
                put("x-message-ttl", TimeUnit.MINUTES.toMillis(httpInvokerProperties.getConnectionRequestTimeout()));
            }
        });
        simpleRabbitmqTemplate.queueBinding(exchange, queue, binding);
    }

    @Override
    public void afterSingletonsInstantiated() {
        simpleRabbitmqTemplate.execute(channel -> {
            try {
                channel.basicQos(1);
                channel.basicConsume(queueKey, true, "10", (consumerTag, message) -> {
                    //返回配置
                    AMQP.BasicProperties replyProperties = cloneBasicProperties(message.getProperties());
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    try {
                        //analysis
                        ObjectInputStream objectInputStream = createObjectInputStream(new ByteArrayInputStream(message.getBody()));
                        RemoteInvocation invocation = remoteInvocationFactory.doReadRemoteInvocation(objectInputStream);
                        Type returnType = invocation.getReturnType(getService());

                        //invoke
                        RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
                        encoder.writeRemoteInvocationResult(outputStream, returnType == null ? Object.class : returnType, result);
                    } catch (Exception ex) {
                        //ignore exception
                        logger.warn("rabbitmq reply message error " + ex.getMessage());
                        replyProperties.appendPropertyDebugStringTo(new StringBuilder(ex.getMessage()));
                    }
                    //result
                    channel.basicPublish("", message.getProperties().getReplyTo(), replyProperties, outputStream.toByteArray());
                }, consumerTag -> System.out.println("取消回调"), (consumerTag, sig) -> {
                    System.out.println("停止" + channel.isOpen());
                    //再次调用
                    if (listenerCount < 10 && !Thread.interrupted()) {
                        try {
                            Thread.sleep(1000 * 5);
                            afterSingletonsInstantiated();
                        } catch (Exception ex) {
                            //ignore exception
                        }
                    }
                    listenerCount++;
                });
            } catch (Exception ex) {
                throw new IllegalArgumentException(String.format("listener %s error", queueKey));
            }
            return null;
        });
    }

    private AMQP.BasicProperties cloneBasicProperties(AMQP.BasicProperties properties) {
        return new AMQP.BasicProperties.Builder()
                .correlationId(properties.getCorrelationId())
                .replyTo(properties.getReplyTo())
                .headers(Optional.ofNullable(properties.getHeaders()).orElse(new HashMap<>()))
                .contentType(properties.getContentType())
                .appId(properties.getAppId())
                .clusterId(properties.getClusterId())
                .deliveryMode(properties.getDeliveryMode())
                .contentEncoding(properties.getContentEncoding())
                .messageId(properties.getMessageId())
                .type(properties.getType())
                .userId(properties.getUserId())
                .build();
    }
}
